<?php
namespace App\Admin\Controllers\OverSeasIn;

use App\Importer\Delivery\FBAImporter;
use App\Models\OverSeasIn\MarksPDF;
use SnappyPdf;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class OSMarksCreateUploadController extends AdminController{

    protected $title = '生成箱唛(上传)';

    protected function grid()
    {
        return view('overseas-in.os-marks-create.upload.index');
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $template = $request->get('template');
            $deliveryNo = $request->get('delivery_no');
            $deliveryNo = strtoupper($deliveryNo);
            $re = $this->{'_import'.$template}($file,$deliveryNo);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _import1(UploadedFile $file,$deliveryNo)
    {
        try {
            $data = Excel::toArray(new FBAImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $boxes = 0;
            $marks = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $box = $row[1] ? trim($row[1]) : '';
                $qty = $row[2] ? trim($row[2]) : '';
                if(!$sku || !$box || !$qty){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                // if(!in_array($sku,$arr)){
                //     $arr[$count] = $sku;
                // }else{
                //     $errors[$count] = '重复记录';
                //     continue;
                // }
                $boxes += intval($box);
                $temp = [
                    'sku' => $sku,
                    'box' => $box,
                    'qty' => $qty,
                ];
                $marks[] = $temp;
            }
            if(empty($marks)){
                $errors[] = '无数据';
            }
            if(!empty($errors)){
                return RExcel::importResult($errors);
            }
            DB::beginTransaction();
            $pdf = SnappyPdf::loadView('overseas-in.os-marks-create.template.1',compact('marks','boxes'))
                ->setOption('page-height','100')
                ->setOption('page-width','100');
            $path = MarksPDF::storePath($deliveryNo,1);
            $pdf->save($path);
            MarksPDF::storeFile($deliveryNo,1);
            DB::commit();
            return ['flag' => true,'data' => $file->getClientOriginalName()];
        } catch (\Exception $e) {
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _import2(UploadedFile $file,$deliveryNo)
    {
        try {
            $data = Excel::toArray(new FBAImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $boxes = 0;
            $marks = [];
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $box = $row[1] ? trim($row[1]) : '';
                $qty = $row[2] ? trim($row[2]) : '';
                if(!$sku || !$box || !$qty){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                // if(!in_array($sku,$arr)){
                //     $arr[$count] = $sku;
                // }else{
                //     $errors[$count] = '重复记录';
                //     continue;
                // }
                $boxes += intval($box);
                $temp = [
                    'sku' => $sku,
                    'box' => $box,
                    'qty' => $qty,
                ];
                $marks[] = $temp;
            }
            if(empty($marks)){
                $errors[] = '无数据';
            }
            if(!empty($errors)){
                return RExcel::importResult($errors);
            }
            DB::beginTransaction();
            $pdf = SnappyPdf::loadView('overseas-in.os-marks-create.template.2',compact('marks','boxes'))
                ->setOption('page-height','100')
                ->setOption('page-width','100');
            $path = MarksPDF::storePath($deliveryNo,2);
            $pdf->save($path);
            MarksPDF::storeFile($deliveryNo,2);
            DB::commit();
            return ['flag' => true,'data' => $file->getClientOriginalName()];
        } catch (\Exception $e) {
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
